#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <cerrno>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <functional>

namespace Server
{
    using namespace std;

    typedef function<void(string, uint16_t, string)> func_t;
    class udpServer
    {
    private:
        uint16_t _port;
        string _ip;
        int _sockfd;
        func_t _callback;

    public:
        udpServer(const func_t& cb, const uint16_t& port, const string& ip = "0.0.0.0")
        : _port(port), _ip(ip), _sockfd(-1), _callback(cb)
        {}

        void InitServer()
        {
            // 1. 创建socket
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if(_sockfd == -1)
            {
                cerr << "socket error: " << errno << " : " << strerror(errno) << endl;
                exit(2);
            }
            cout << "socket success: " << " : " << _sockfd << endl;
            // 2. 绑定(端口号和IP)
            struct sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);  // 给别人发消息，你的port和ip要发送给对方，经过网络，转为网络字节序
            //local.sin_addr.s_addr = inet_addr(_ip.c_str()); //inet_addr 将点分十进制转为整，然后转为网络字节序
            local.sin_addr.s_addr = INADDR_ANY; // 任意地址bind

            int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
            if(n == -1)
            {
                 cerr << "bind error: " << errno << " : " << strerror(errno) << endl;
                exit(3);
            }
            // UDP Server 的预备工作完成
        }

        void Start()
        {
            // 服务器本质是一个死循环
            char buffer[1024];
            while(1)
            {
                // 读取数据
                struct sockaddr_in peer; // 输出型参数，保存发过来信息主机的IP和port
                socklen_t len = sizeof(peer); //必填: len必须设定为peer的大小。做输入时告诉传过来的peer长度是多少
                ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);

                if(s > 0)
                {
                    buffer[s] = 0;
                    string clientip = inet_ntoa(peer.sin_addr); // 网络转主机并且转成点分十进制
                    uint16_t clientport = ntohs(peer.sin_port);
                    string message = buffer; 

                    cout << clientip <<"[" << clientport << "]# " << message << endl;

                    // 我们只把数据读上来就完了吗？对数据做处理
                    _callback(clientip, clientport, message);
                }
            }
        }   

        ~udpServer()
        {}
    };
    
} // namespace Server
